/**
 * 
 */
package qy.jalgotrade.technical.stats;

import org.apache.commons.math3.stat.descriptive.moment.StandardDeviation;

import qy.jalgotrade.dataseries.SequenceDataSeries;
import qy.jalgotrade.technical.EventBasedFilter;
import qy.jalgotrade.technical.EventWindow;

/**
 * @author c-geo
 *
 */
public class StdDev extends EventBasedFilter<Double> {

	/**
	 * 
	 * @author c-geo
	 *
	 */
	protected class StdDevEventWindow extends EventWindow<Double> {

		private StandardDeviation stdDev;

		private int __ddof;

		/**
		 * 
		 * @param period
		 */
		public StdDevEventWindow(int period) {

			this(period, 0);
		}

		/**
		 * 
		 * @param period
		 * @param ddof
		 */
		public StdDevEventWindow(int period, int ddof) {

			super(period, Double.class);
			assert period > 0;
			__ddof = ddof;
			if (__ddof == 0) {
				stdDev = new StandardDeviation(false);
			} else {
				stdDev = new StandardDeviation(true);
			}
		}

		/*
		 * (non-Javadoc)
		 * 
		 * @see qy.jalgotrade.technical.EventBasedFilter.EventWindow#getValue()
		 */
		@Override
		public Double getValue() {

			double ret = Double.NaN;
			if (windowFull()) {

//				ret = stdDev.evaluate(((DoubleList) getValues()).toDoubleArray());
				ret = stdDev.evaluate((double[]) toPrimitiveArray());
			}
			return ret;
		}
	}

	/**
	 * 
	 * @param dataSeries
	 * @param period
	 * @throws Exception
	 */
	public StdDev(SequenceDataSeries<Double> dataSeries, int period) throws Exception {

		this(dataSeries, period, 0, 0);
	}

	/**
	 * 
	 * @param dataSeries
	 * @param period
	 * @param ddof
	 * @throws Exception
	 */
	public StdDev(SequenceDataSeries<Double> dataSeries, int period, int ddof) throws Exception {

		this(dataSeries, period, ddof, 0);
	}

	/**
	 * 
	 * @param dataSeries
	 * @param period
	 * @param ddof
	 * @param maxLen
	 * @throws Exception
	 */
	public StdDev(SequenceDataSeries<Double> dataSeries, int period, int ddof, int maxLen) throws Exception {

		super(maxLen);
		StdDevEventWindow win = new StdDevEventWindow(period, ddof);
		_init(dataSeries, win);
	}
}
